package cmd

import (
	"encoding/base64"
	"errors"
	"fmt"
	"github.com/spf13/cobra"
	"os"
)

var input string
var output string

var base64Cmd = &cobra.Command{
	Use:   "base64",
	Short: "base64 decode and write to file",
	Long:  `base64 decode and write to file`,
	PreRunE: func(cmd *cobra.Command, args []string) error {

		if len(input) == 0 {
			return errors.New("no input files")
		}
		fi, e := os.Stat(input)
		if e != nil {
			return e
		}
		if fi == nil {
			return errors.New("file " + input + " not exists.")
		}
		if fi.IsDir() {
			return errors.New("file " + input + " is a dir.")
		}
		fio, eo := os.Stat(output)
		if eo == nil || fio != nil {
			return errors.New("file " + output + " is already exists.")
		}

		return nil

	},
	Run: func(cmd *cobra.Command, args []string) {
		bs, e := os.ReadFile(input)
		if e != nil {
			panic(e)
		}
		bso, e := base64.StdEncoding.DecodeString(string(bs))
		if e != nil {
			panic(e)
		}
		if len(bso) == 0 {
			panic("nothing was read.")
		}
		e = os.WriteFile(output, bso, 664)
		if e != nil {
			panic(e)
		}
		fmt.Println("file " + output + " written.")

	},
}

func init() {
	base64Cmd.Flags().StringVarP(&input, "input", "i", "", "path to input file contains base64 string")
	base64Cmd.Flags().StringVarP(&output, "output", "o", "output.tmp", "path to output file")

	rootCmd.AddCommand(base64Cmd)
}
